package org.kinglone.common.util;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;


/**
 * 
 * 名称： FileUtils <br>
 * 描述： 文件读写工具
 * 
 */
public class FileUtils {
	private static Logger log = Logger.getLogger(FileUtils.class);

	/**
	 * 
	 * 描述：读取文件扩展名
	 * 
	 * @param fileName 文件名
	 * @return
	 * @version: 1.0
	 * @date: 2011-1-11 下午06:00:27
	 */
	public static String getExtension(String fileName) {
		return FilenameUtils.getExtension(fileName);
	}

	/**
	 * 
	 * 描述：强制删除文件
	 * 
	 * @param file
	 * @version: 1.0
	 * @date: 2011-1-11 下午06:01:37
	 */
	public static void forceDelete(File file) {
		try {
			org.apache.commons.io.FileUtils.forceDelete(file);
		} catch (IOException e) {
			log.error(e);
		}
	}

	/**
	 * 
	 * 描述：打开文件输入流
	 * 
	 * @param file
	 * @return
	 * @throws IOException
	 * @version: 1.0
	 * @date: 2011-1-11 下午06:16:50
	 */
	public static FileInputStream openInputStream(File file) throws IOException {
		return org.apache.commons.io.FileUtils.openInputStream(file);
	}

	
	/**
	 * 生成指定文件
	 * @param path 指定文件路径
	 * @param in InputStream 文件输入流
	 * @author cq
	 */
	public static void createFile(String path,InputStream in) throws IOException{
		File file = new File(path);
		if (file.exists() && file.canWrite()) {
			file.delete();
		}
		if (!file.exists()) {
			byte[] buffer = new byte[512];
			BufferedOutputStream out = null;
			try {
				try {
					out = new BufferedOutputStream(new FileOutputStream(
							file));
					while (true) {
						int readed = in.read(buffer);
						if (readed > -1) {
							out.write(buffer, 0, readed);
						} else {
							break;
						}
					}
				} finally {
					if (out != null) {
						out.close();
					}
				}
			} catch (IOException e) {
				throw new IOException("生成文件出错");
			}
		}
	}
	
	/**
	 * 
	 * Description: 保存图片 
	 * Author: ZhangJiuWang
	 * Version: 1.0
	 * Create Date Time: 2017年5月17日 下午1:57:14.
	 * Update Date Time: 
	 * @see 
	 * @param request 表单提交请求
	 * @param uploadFileName upload下要分存的文件夹名称
	 * @param size	文件大小限制  单位bit;
	 * @param width 图片宽度限制
	 * @param height 图片高度限制  图片宽度限制和高度限制均不为null时判断图片长宽，否则不做判断
	 * @return	键-form中input的name属性  值-图片保存的相对地址
	 */
	public static Map<String,String> saveByRequest(HttpServletRequest request,String uploadFileName,Integer size,Integer width,Integer height){
		Map<String,String> map=new HashMap<String,String>();
		FileItemFactory factory=new DiskFileItemFactory(); 
		ServletFileUpload upload=new ServletFileUpload(factory);
		try {
			List<FileItem> lstForms = upload.parseRequest(request);
			for (FileItem fileItem : lstForms) {
				// 判断每表单元素否普通表单
				if (fileItem.isFormField()) {
				} else {
					//文件上传路径  保存至tomcat下
					/*String path=request.getSession().getServletContext().getRealPath("/");*/
										
					//1、保存头像到upload/user
					//获取保存路径的绝对地址
					/*String path = request.getSession().getServletContext().getRealPath("\\");*/
					String path=PropertieUtil.getValue("config.properties", "upload_url");
					//相对保存路径
					//String relativePath="resources\\upload\\"+uploadFileName+"\\"+DateUtils.format(new Date(), "yyyyMMdd")+"\\";
					String relativePath="/upload/"+uploadFileName+"/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";
					
					//获取文件格式，并用时间戳重命名文件
					String fileName = fileItem.getName();
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
					String newFileName=String.valueOf(new Date().getTime())+fileName.substring(fileName.lastIndexOf("."));
					
					System.out.println("上传路径："+path);
					System.out.println("相对路径："+relativePath);
					System.out.println("新文件名路径："+newFileName);
					System.out.println(fileItem.getFieldName());
					
					//判断要存储的文件夹是否存在，不存在则创建
					String holePath=path+relativePath;
					System.out.println("完整存储路径："+holePath);
					File f=new File(holePath);
					if(!f.exists()){
						f.mkdirs();
					}
					
					//判断文件是否超出大小限制
					if(fileItem.getSize()>size){
						System.out.println(fileItem.getSize());
						map.put(fileItem.getFieldName(), "error");
					}else{
						//保存到新文件
						File file=new File(holePath+newFileName);
						fileItem.write(file);
						
						if(width!=null&&height!=null){
							Integer src_width=-1;
							Integer src_height=-1;
							try {
								InputStream is = new FileInputStream(file);  
								BufferedImage src = javax.imageio.ImageIO.read(is); 
								src_width=src.getWidth(null);
								System.out.println("宽度："+src_width);
								src_height=src.getHeight(null);
								System.out.println("高度："+src_height);
								if(src_width<=width&&src_height<=height){
									//取相对路径名作为返回值
									map.put(fileItem.getFieldName(), relativePath+newFileName);
								}
								else {
									map.put(fileItem.getFieldName(), "error");
								}
							} catch (Exception e) {
								e.printStackTrace();
								map.put(fileItem.getFieldName(), "error");
							}
							
							
						}else{
							//取相对路径名作为返回值
							map.put(fileItem.getFieldName(), relativePath+newFileName);
						}
					}
				}
			}
			return map;
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 上传音乐
	 * @param request
	 * @param uploadFileName
	 * @param size
	 * @param width
	 * @param height
	 * @return
	 */
	public static Map<String,String> saveMusicByRequest(HttpServletRequest request,String uploadFileName){
		Map<String,String> map=new HashMap<String,String>();
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload=new ServletFileUpload(factory);
		try {
			List<FileItem> lstForms = upload.parseRequest(request);
			for (FileItem fileItem : lstForms) {
				// 判断每表单元素否普通表单
				if (fileItem.isFormField()) {
				} else {

					String path=PropertieUtil.getValue("config.properties", "upload_url");
					//相对保存路径
					//String relativePath="resources\\upload\\"+uploadFileName+"\\"+DateUtils.format(new Date(), "yyyyMMdd")+"\\";
					String relativePath="/upload/"+uploadFileName+"/"+DateUtils.format(new Date(), "yyyyMMdd")+"/";

					//获取文件格式，并用时间戳重命名文件
					String fileName = fileItem.getName();
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
					String newFileName=String.valueOf(new Date().getTime())+fileName.substring(fileName.lastIndexOf("."));

					System.out.println("上传路径："+path);
					System.out.println("相对路径："+relativePath);
					System.out.println("新文件名路径："+newFileName);
					System.out.println(fileItem.getFieldName());

					//判断要存储的文件夹是否存在，不存在则创建
					String holePath=path+relativePath;
					System.out.println("完整存储路径："+holePath);
					File f=new File(holePath);
					if(!f.exists()){
						f.mkdirs();
					}

					//保存到新文件
					File file=new File(holePath+newFileName);
					fileItem.write(file);
					//取相对路径名作为返回值
					map.put(fileItem.getFieldName(), relativePath+newFileName);
				}
			}
			return map;
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}



	/**
	 * 
	 * Description: 单文件保存
	 * Author: ZhangJiuWang
	 * Version: 1.0
	 * Create Date Time: 2017年5月17日 下午2:06:42.
	 * Update Date Time: 
	 * @see 
	 * @param fileItem 文件上传项
	 * @param path	项目路径
	 * @param savePath	相对路径
	 * @param size 文件大小限制  单文bit
	 * @return
	 */
	public static String singleSave(FileItem  fileItem,String path,String relativePath,Long size){
		try{
			String fileName = fileItem.getName();
			fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
			String newFileName=String.valueOf(new Date().getTime())+fileName.substring(fileName.lastIndexOf("."));
			String holePath=path+relativePath;
			System.out.println("完整存储路径："+holePath);
			File f=new File(holePath);
			if(!f.exists()){
				f.mkdirs();
			}
			
			//判断文件是否超出大小限制
			if(fileItem.getSize()>size){
				System.out.println(fileItem.getSize());
				return "error";
			}else{
				//保存到新文件
				fileItem.write(new File(holePath+newFileName));
				//取相对路径名作为返回值
				return relativePath+newFileName;
			}
		}catch(Exception ex){
			ex.printStackTrace();
			return "error";
		}
	}
	
	
	
	public static void main(String[] args) {
		System.out.println(getExtension("...xx"));
		System.out.println(getExtension("xxb"));
		System.out.println(getExtension(".xx"));
		System.out.println(getExtension("mm.gif.jpg"));
		System.out.println(getExtension("mm.gif"));
	}
}
